using Avalonia;
using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using AvaloniaDrawingPad.Models;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;

namespace AvaloniaDrawingPad.Views
{
    public partial class ShortcutSettingsWindow : Window
    {
        public ObservableCollection<ShortcutItem> Shortcuts { get; private set; } = new ObservableCollection<ShortcutItem>();

        public ShortcutSettingsWindow()
        {
            InitializeComponent();
            
            try
            {
                // 初始化Shortcuts属性
                var manager = ShortcutManager.Instance;
                if (manager != null && manager.Shortcuts != null)
                {
                    foreach (var shortcut in manager.Shortcuts)
                    {
                        Shortcuts.Add(shortcut);
                    }
                    
                    Debug.WriteLine($"已加载 {Shortcuts.Count} 个快捷键");
                }
                else
                {
                    Debug.WriteLine("ShortcutManager.Instance 或 Shortcuts 为 null");
                    
                    // 如果无法获取快捷键，添加一些默认值以便测试
                    Shortcuts.Add(new ShortcutItem("测试1", "测试描述1", Key.A, KeyModifiers.Control));
                    Shortcuts.Add(new ShortcutItem("测试2", "测试描述2", Key.B, KeyModifiers.Shift));
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"初始化快捷键时出错: {ex.Message}");
            }
            
            // 设置数据上下文
            DataContext = this;
            
            // 确保DataGrid能找到并显示数据
            var dataGrid = this.FindControl<DataGrid>("ShortcutsDataGrid");
            if (dataGrid != null)
            {
                dataGrid.ItemsSource = Shortcuts;
                Debug.WriteLine("已设置DataGrid的ItemsSource");
            }
            else
            {
                Debug.WriteLine("找不到ShortcutsDataGrid控件");
            }
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }

        private void ShortcutsDataGrid_DoubleTapped(object? sender, Avalonia.Input.TappedEventArgs e)
        {
            EditSelectedShortcut();
        }

        private void EditShortcut_Click(object? sender, RoutedEventArgs e)
        {
            EditSelectedShortcut();
        }

        private void EditSelectedShortcut()
        {
            var dataGrid = this.FindControl<DataGrid>("ShortcutsDataGrid");
            if (dataGrid?.SelectedItem is ShortcutItem selectedShortcut)
            {
                var dialog = new ShortcutEditDialog(selectedShortcut);
                dialog.ShowDialog(this);
            }
        }

        private void ResetShortcuts_Click(object? sender, RoutedEventArgs e)
        {
            // 创建一个新的ShortcutManager实例来重置所有快捷键
            var newManager = ShortcutManager.Instance;
            
            // 清空当前快捷键列表
            Shortcuts.Clear();
            
            // 添加默认快捷键
            foreach (var shortcut in newManager.Shortcuts)
            {
                Shortcuts.Add(shortcut);
            }
        }

        private void Close_Click(object? sender, RoutedEventArgs e)
        {
            Close();
        }
    }
    
    public class ShortcutEditDialog : Window
    {
        private readonly ShortcutItem _shortcut;
        private Key _newKey = Key.None;
        private KeyModifiers _newModifiers = KeyModifiers.None;
        private TextBlock _keyDisplayTextBlock;
        
        public ShortcutEditDialog(ShortcutItem shortcut)
        {
            _shortcut = shortcut;
            
            // 初始化窗口属性
            Title = $"编辑快捷键 - {shortcut.Name}";
            Width = 400;
            Height = 200;
            WindowStartupLocation = WindowStartupLocation.CenterOwner;
            
            // 创建UI
            var grid = new Grid
            {
                RowDefinitions = new RowDefinitions("Auto,Auto,*,Auto"),
                Margin = new Thickness(20)
            };
            
            var titleTextBlock = new TextBlock
            {
                Text = $"为\"{shortcut.Name}\"设置新的快捷键",
                FontSize = 16,
                FontWeight = Avalonia.Media.FontWeight.Bold,
                Margin = new Thickness(0, 0, 0, 10)
            };
            Grid.SetRow(titleTextBlock, 0);
            
            var instructionTextBlock = new TextBlock
            {
                Text = "请按下新的快捷键组合（按ESC取消）",
                Margin = new Thickness(0, 0, 0, 10)
            };
            Grid.SetRow(instructionTextBlock, 1);
            
            _keyDisplayTextBlock = new TextBlock
            {
                Text = shortcut.KeyDisplay,
                FontSize = 16,
                HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Center,
                VerticalAlignment = Avalonia.Layout.VerticalAlignment.Center,
                Padding = new Thickness(10),
                Background = new Avalonia.Media.SolidColorBrush(Avalonia.Media.Colors.LightGray),
                Width = 200,
                Height = 40
            };
            Grid.SetRow(_keyDisplayTextBlock, 2);
            
            var buttonPanel = new StackPanel
            {
                Orientation = Avalonia.Layout.Orientation.Horizontal,
                HorizontalAlignment = Avalonia.Layout.HorizontalAlignment.Right,
                Margin = new Thickness(0, 10, 0, 0)
            };
            Grid.SetRow(buttonPanel, 3);
            
            var okButton = new Button
            {
                Content = "确定",
                Margin = new Thickness(0, 0, 10, 0)
            };
            okButton.Click += OkButton_Click;
            
            var cancelButton = new Button
            {
                Content = "取消"
            };
            cancelButton.Click += CancelButton_Click;
            
            buttonPanel.Children.Add(okButton);
            buttonPanel.Children.Add(cancelButton);
            
            grid.Children.Add(titleTextBlock);
            grid.Children.Add(instructionTextBlock);
            grid.Children.Add(_keyDisplayTextBlock);
            grid.Children.Add(buttonPanel);
            
            Content = grid;
            
            // 添加键盘事件处理
            KeyDown += ShortcutEditDialog_KeyDown;
        }
        
        private void ShortcutEditDialog_KeyDown(object? sender, KeyEventArgs e)
        {
            // 如果按下ESC键，取消编辑
            if (e.Key == Key.Escape)
            {
                Close();
                return;
            }
            
            // 忽略单独的修饰键
            if (e.Key == Key.LeftCtrl || e.Key == Key.RightCtrl ||
                e.Key == Key.LeftShift || e.Key == Key.RightShift ||
                e.Key == Key.LeftAlt || e.Key == Key.RightAlt)
            {
                return;
            }
            
            // 保存新的快捷键
            _newKey = e.Key;
            _newModifiers = e.KeyModifiers;
            
            // 更新显示
            UpdateKeyDisplay();
            
            e.Handled = true;
        }
        
        private void UpdateKeyDisplay()
        {
            string display = "";
            
            if (_newModifiers.HasFlag(KeyModifiers.Control))
                display += "Ctrl+";
            
            if (_newModifiers.HasFlag(KeyModifiers.Shift))
                display += "Shift+";
            
            if (_newModifiers.HasFlag(KeyModifiers.Alt))
                display += "Alt+";
            
            if (_newKey != Key.None)
                display += _newKey.ToString();
            
            _keyDisplayTextBlock.Text = display;
        }
        
        private void OkButton_Click(object? sender, RoutedEventArgs e)
        {
            if (_newKey != Key.None)
            {
                // 更新快捷键
                _shortcut.Key = _newKey;
                _shortcut.Modifiers = _newModifiers;
            }
            
            Close();
        }
        
        private void CancelButton_Click(object? sender, RoutedEventArgs e)
        {
            Close();
        }
    }
} 